/*
 * @Author: jiejie
 * @Github: https://github.com/jiejieTop
 * @Date: 2019-12-26 19:11:34
 * @LastEditTime : 2019-12-28 01:51:38
 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
 */
#include "salof_defconfig.h"

#ifdef SALOF_USING_LOG

salof_mutex  _salof_mutex = {0};
salof_sem  _salof_sem = {0};
void *salof_alloc(unsigned int size)
{
    return malloc(size);
}

void salof_free(void *mem)
{
    free(mem);
}

salof_tcb salof_task_create(const char *name,
                            void (*task_entry)(void *param),
                            void * const param,
                            unsigned int stack_size,
                            unsigned int priority,
                            unsigned int tick)
{
    salof_tcb task;

    pthread_attr_t attr;
    struct sched_param salof_priority;
    salof_priority.sched_priority = priority;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, stack_size);
    pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
    pthread_attr_setschedparam(&attr, &salof_priority);

    int res = pthread_create(&task, &attr, (void* (*)(void*))task_entry, param);
    if (0 != res)
    {
        printf("thread create failed");
        return NULL;
    }
    return task;
}

salof_mutex salof_mutex_create(void)
{
    pthread_mutex_init(&_salof_mutex, NULL);
    return _salof_mutex;
}

void salof_mutex_delete(salof_mutex mutex)
{
    pthread_mutex_destroy(&mutex);
}

int salof_mutex_pend(salof_mutex mutex, unsigned int timeout)
{

    if (pthread_mutex_lock(&mutex) != 0)
        return -1;
    return 0;
}

int salof_mutex_post(salof_mutex mutex)
{
    if (pthread_mutex_unlock(&mutex)!= 0)
        return -1;
    return 0;
}

salof_sem salof_sem_create(void)
{
    sem_init(&_salof_sem, 0, 0);
    return _salof_sem;
}

void salof_sem_delete(salof_sem sem)
{
    sem_close(&sem);
}


int salof_sem_pend(salof_sem sem, unsigned int timeout)
{

    struct timespec abs_timeout;
    abs_timeout.tv_nsec = timeout;
    if(sem_timedwait(&sem, &abs_timeout) != 0)
        return -1;
    return 0;
}

int salof_sem_post(salof_sem sem)
{
    if(sem_post(&sem) != 0)
        return -1;
    return 0;
}


unsigned int salof_get_tick(void)
{
    extern long long aos_sys_tick_get();
    return aos_sys_tick_get();
}

char *salof_get_task_name(void)
{
    return NULL;
}

int send_buff(char *buf, int len)
{
    extern int32_t aos_debug_printf(const char *fmt, ...);
    aos_debug_printf("\r%s", buf);

    return len;
}

#endif
